package com.hk.blog.controller;

import com.hk.blog.domain.ArticleInfo;
import com.hk.blog.service.ArticleInfoService;
import com.hk.blog.service.CategoryInfoService;
import com.hk.blog.service.UserInfoService;
import com.hk.commons.JsonResult;
import com.hk.commons.Status;
import com.hk.commons.query.Order;
import com.hk.commons.query.QueryModel;
import com.hk.commons.query.page.SimpleQueryPage;
import com.hk.commons.util.StringUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Kevin
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("home")
public class HomePageController {

    private final UserInfoService userInfoService;

    private final ArticleInfoService articleInfoService;

    private final CategoryInfoService categoryInfoService;

    @GetMapping(path = "{username}")
    public JsonResult<?> homePage(@PathVariable String username) {
        var userInfo = userInfoService.findByUsername(username);
        if (userInfo.isEmpty()) {
            return new JsonResult<>(Status.NOT_FOUND);
        }
        var user = userInfo.get();
        var result = new HashMap<String, Object>(3);
        result.put("userInfo", Map.of("nickName", StringUtils.defaultIfEmpty(user.getNickName(), user.getUsername()),
                "email", StringUtils.defaultIfEmpty(user.getEmail(), StringUtils.EMPTY),
                "iconPath", StringUtils.defaultIfEmpty(user.getIconPath(), StringUtils.EMPTY),
                "remark", StringUtils.defaultIfEmpty(user.getRemark(), StringUtils.EMPTY)));
        result.put("categoryList", categoryInfoService.findByUserId(user.getId()));
        var queryModel = new QueryModel<ArticleInfo>();
        queryModel.setPageSize(5);
        queryModel.setParam(new ArticleInfo().setUserId(user.getId()));
        queryModel.addOrders(Order.desc("lastModifiedDate"));
        var page = articleInfoService.queryForPage(queryModel);
        for (var item : page.getData()) {
            item.setContent(StringUtils.substringBefore(item.getContent(), StringUtils.LF));
        }
        result.put("articlePage", page);
        return JsonResult.success(result);
    }

    @Data
    @Accessors(chain = true)
    public static class HomePageSearch implements Serializable {

        private Long categoryId;

        private String account;

        private String keyword;
    }

    /**
     * 主页根据 categoryId 与 搜索关键字查询
     */
    @PostMapping("search")
    public JsonResult<?> search(@RequestBody QueryModel<HomePageSearch> query) {
        var param = query.getParam();
        if (param == null || StringUtils.isEmpty(param.getAccount())) {
            return JsonResult.success(new SimpleQueryPage<>(query, Collections.emptyList(), 0L));
        }
        var userInfo = userInfoService.findByUsername(param.getAccount());
        if (userInfo.isEmpty()) {
            return JsonResult.success(new SimpleQueryPage<>(query, Collections.emptyList(), 0L));
        }
        var user = userInfo.get();
        var queryModel = new QueryModel<ArticleInfo>();
        queryModel.setPageSize(query.getPageSize());
        queryModel.setPageIndex(query.getPageIndex());
        queryModel.setParam(new ArticleInfo().setUserId(user.getId())
                .setCategoryId(query.getParam().getCategoryId())
                .setTitle(query.getParam().getKeyword()));
        queryModel.addOrderToFirst(Order.asc("title"));
        var page = articleInfoService.queryForPage(queryModel);
        for (var item : page.getData()) {
            item.setContent(StringUtils.substringBefore(item.getContent(), StringUtils.LF));
        }
        return JsonResult.success(page);
    }

}
